//
//  LocalCacheUtil.swift
//  maste
//
//  Created by 帽子 on 2020/8/15.
//  Copyright © 2020 帽子. All rights reserved.
//

import SwiftUI

final class LocalCacheUtil {
    private static var fileManager: FileManager = FileManager()

    private static var cachePath: String {
        NSSearchPathForDirectoriesInDomains(.cachesDirectory, .allDomainsMask, true).first!
    }

    private static var encoder: JSONEncoder {
        JSONEncoder()
    }

    private static var decoder: JSONDecoder {
        JSONDecoder()
    }

    /* 将参数value 编码保存
     * filename: 保存的文件名称
     * value: 需要保存的值
     */
    static func save<T: Encodable>(filename: String, value: T) -> Bool {
        let atPath = cachePath + "/" + filename
        guard let data = try? encoder.encode(value) else {
            fatalError("解析失败")
        }
        return fileManager.createFile(atPath: atPath, contents: data, attributes: nil)
    }

    /* 通过传入的 文件名 查找
     * filename: 保存的文件名称
     */
    static func getAll<T: Decodable>(filename: String) -> T {
        let ts = Array<T>()
        let atPath = cachePath + "/" + filename
        if fileManager.fileExists(atPath: atPath) {
            let data = fileManager.contents(atPath: atPath) ?? Data()
            if !data.isEmpty {
                do {
                    return try decoder.decode(T.self, from: data)
                } catch {
                    print("解析失败 \(error)")
                    return ts as! T
                }
            } else {
                print("\(filename) 缓存文件内容为空")
                return ts as! T
            }
        } else {
            fileManager.createFile(atPath: atPath, contents: Data([]), attributes: nil)
            print("\(filename) 缓存文件初始化")
            return ts as! T
        }
    }

    /* 清除缓存文件
     * filename: 文件名称
     */
    static func clearCache(filename: String) {
        let atPath = cachePath + "/" + filename
        if fileManager.fileExists(atPath: atPath) {
            try? fileManager.removeItem(atPath: atPath)
        }
    }
}
